﻿namespace com.stifel.BranchMgmt
{
    using System;
    using System.Collections.Generic;
    using System.Net.Mail;

    using com.stifel.BranchMgmtDao;
    using com.stifel.Extensions.DoubleExtensions;
    using com.stifel.SharePoint;

    using Microsoft.SharePoint.Administration;

    public partial class SunsetBranchLease : SPJobDefinition
    {
        #region Fields

        public const string JOBNAME = "SunsetBranchLease";
        public const string JOBTITLE = " Stifel :: Branch Lease Expiration Notifier";

        const string JOBDESCRIPTION = "Notifies the configured group of the impending expiration of branch leases. For the current configuration, see the site-collection list: Stifel Branch Configuration.";

        StifelBranchConfiguration _configuration;

        #endregion Fields

        #region Constructors

        public SunsetBranchLease( )
            : base()
        {
        }

        public SunsetBranchLease( string name, SPWebApplication webApplication )
            : base(name, webApplication, null, SPJobLockType.Job)
        {
        }

        #endregion Constructors

        #region Properties

        public override string Description
        {
            get
            {
                return JOBDESCRIPTION;
            }
        }

        public override string DisplayName
        {
            get
            {
                return JOBTITLE;
            }
        }

        public string JobTitle
        {
            get
            {
                return JOBNAME;
            }
        }

        StifelBranchConfiguration configuration
        {
            get
            {
                if ( _configuration == null )
                {
                    StifelBranchConfigurationDao dao = new StifelBranchConfigurationDao( );
                    _configuration = dao.Get( );
                }
                return _configuration;
            }
        }

        #endregion Properties

        #region Methods

        public override void Execute( Guid targetInstanceId )
        {
            try
            {
                SPWebApplication spWebApplication = this.Parent as SPWebApplication;
                if ( spWebApplication == null )
                    throw new Exception( "Web application could not be obtained." );

                issueNotifications( );

            }
            catch ( Exception e )
            {
                CustomLoggingService.LogError( CustomLoggingService.Area.TimerJob, e, "Error in Execute" );
            }
        }

        protected override bool HasAdditionalUpdateAccess( )
        {
            return true;
        }

        Guid addNotification( int branchLookupId, string title, string notification, string itemUrl, string siteurl )
        {
            Guid uniqueId = Guid.Empty;
            if ( StifelNotificationDao.ListExists( siteurl ) )
            {
                StifelNotification value = new StifelNotification
                {
                    BranchLookupId = branchLookupId,
                    BranchNotification = notification,
                    BranchNotificationURL = itemUrl,
                    Title = title
                };
                StifelNotificationDao dao = new StifelNotificationDao( siteurl );
                uniqueId = dao.Add( value );
            }
            return uniqueId;
        }

        void issueNotifications( )
        {
            DateTime target = configuration.TargetBranchLeaseExpirationDate;
            int repeatEveryNDays = configuration.RepeatNotificationEveryNDaysUntilBranchLeaseResolutionAsInteger;
            DateTime today = DateTime.Now;

            string liveBranchSite = configuration.ProductionSiteURLForTheLiveBranchesUrl;

            StifelBranchLeaseDao dao = new StifelBranchLeaseDao( liveBranchSite );
            List<StifelBranchLease> l = dao.GetExpiring( target );
            foreach ( StifelBranchLease o in l )
            {
                bool sendEmail = configuration.BranchLeaseSendEmail.HasValue ? configuration.BranchLeaseSendEmail.Value : false;

                string title = configuration.FormatNotificationTitle( StifelBranchConfiguration.Area.Lease, o.ItemUrl, o.Title, o.BranchLookupTitle );
                string notification = configuration.FormatNotification( StifelBranchConfiguration.Area.Lease, o.ItemUrl, o.Title, o.BranchLookupTitle );
                // prior notifications
                if ( o.Notifications.Items.Count > 0 )
                {
                    Notification n = o.Notifications.Items[ o.Notifications.Items.Count - 1 ];
                    if ( n.LastNotified.HasValue )
                    {
                        DateTime repeateDate = n.LastNotified.Value.AddDays( repeatEveryNDays );
                        // is today > or = the date to repeat the notification
                        sendEmail = today.CompareTo( repeateDate ) >= 0;
                    }
                }
                else // no prior notifications
                {
                    if ( StifelNotificationDao.ListExists( configuration.SiteURLForTheBranchLeaseNotificationUrl ) )
                    {
                        addNotification( o.BranchLookupId.Value,title, notification, o.ItemUrl, configuration.SiteURLForTheBranchLeaseNotificationUrl );
                    }
                }

                if ( sendEmail )
                {
                    List<MailAddress> to = configuration.GetSecurityGroupEmailAddresses( StifelBranchConfiguration.Area.Lease, liveBranchSite );
                    if ( to.Count > 0 )
                    {
                        SPSendEmail spSendEmail = new SPSendEmail( );
                        bool ok = spSendEmail.SendEmail( liveBranchSite, title, notification, to );
                    }
                }
            }
        }

        #endregion Methods
    }
}